<!--
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
-->
<!--
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
-->
<template>
  <div>
    <el-form>
      <el-form-item label="角色名称">
        <el-input v-model="name"></el-input>
      </el-form-item>
      <el-form-item label="角色权限">
        <el-tree
          :data="treeData"
          :props="customProps"
          node-key="path"
          show-checkbox
          ref="treeRef"
        ></el-tree>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRole">
          {{ rowData ? "修改角色" : "新增角色" }}
        </el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { routes } from "@/router";
import { rolePost, rolePut } from "@/api/user-api";
export default {
  props: ["rowData"], //区分新增、编辑
  data() {
    return {
      name: "",
      treeData: routes[0].children, //渲染树形组件的数据包
      customProps: {
        // label: "path",
        label: (data) => {
          return data.meta.label;
        },
      },
    };
  },
  methods: {
    async handleRole() {
      // console.log(this.$refs.treeRef.getCheckedKeys());
      let checkedKeys = this.$refs.treeRef.getCheckedKeys(); //获取被勾选的路由
      let newObj = { name: this.name, checkedKeys };
      let res;
      let type;
      if (this.rowData) {
        //修改
        let { objectId } = this.rowData;
        res = await rolePut(objectId, newObj); //同步请求
        type = 1;
        newObj.objectId = objectId;
      } else {
        //新增
        res = await rolePost(newObj);
        type = 2;
        newObj.objectId = res.data.objectId;
      }
      this.$emit("update-role", {
        newObj, //携带objectId
        type,
      });
    },
  },
  mounted() {
    console.log("roleForm组件渲染了");
    if (this.rowData) {
      //修改
      let { name, checkedKeys } = this.rowData;
      this.name = name;
      this.$refs.treeRef.setCheckedKeys(checkedKeys);
    } else {
      //新增
      this.name = "";
      this.$refs.treeRef.setCheckedKeys([]);
    }
  },
};
</script>

<style lang="scss" scoped></style>
